package com.wangyb.wework.service.contact;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.page.PagePlus;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.system.service.ISysDictDataService;
import com.wangyb.wework.bo.ContactAddwayState;
import com.wangyb.wework.entity.contact.*;
import com.wangyb.wework.entity.employee.WwEmployee;
import com.wangyb.wework.enums.ContactAddwayStateEnum;
import com.wangyb.wework.enums.TrackEventEnum;
import com.wangyb.wework.mapper.contact.WwContactMapper;
import com.wangyb.wework.service.IWwEmployeeService;
import com.wangyb.wework.utils.FileUtils;
import com.wangyb.wework.utils.WxStringUtils;
import com.wangyb.wework.utils.ali.AliyunOssUtils;
import com.wangyb.wework.utils.ali.AliyunUpload;
import com.wangyb.wework.vo.WwContactVo;
import com.wangyb.wework.wxApi.ExternalContactResp;
import jodd.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;

/**
 * 联系人（客户列）Service业务层处理
 *
 * @Author: wangyb
 * @Date: 2021/6/30 6:23 下午
 */
@Service
public class WwContactServiceImpl extends ServiceImpl<WwContactMapper, WwContact> implements IWwContactService{
	@Autowired
	private IWwEmployeeService iEmployeeService;

	@Autowired
	private IWwTagService iTagService;

	@Autowired
	private IExternalContactService iExternalContactService;
	@Autowired
	private IWwContactEmployeeService iContactEmployeeService;
	@Autowired
	private IWwContactTagPivotService iWwContactTagPivotService;
	@Autowired
	private RedissonClient redissonClient;
	@Autowired IWwContactTrackService iWwContactTrackService;
	@Autowired
	private ISysDictDataService iSysDictDataService;


	@Override
	public WwContactVo queryById(String id){
		return getVoById(id, WwContactVo.class);
	}

	@Override
	public TableDataInfo<WwContactVo> queryPageList(WwContactQueryBo bo) {
		PagePlus<WwContact, WwContactVo> result = pageVo(PageUtils.buildPagePlus(), buildQueryWrapper(bo), WwContactVo.class);
		result.getRecordsVo().parallelStream().forEach(contactVo -> {

			String avatarUrl = AliyunOssUtils.getUrl(contactVo.getAvatar());
			contactVo.setAvatar(avatarUrl);

			//处理归属成员 begin
			List<WwContactEmployee> contactEmployeeList = iContactEmployeeService.lambdaQuery().eq(WwContactEmployee::getContactId, contactVo.getId()).list();
			Set<Long> employeeIdSet = contactEmployeeList.stream().map(WwContactEmployee::getEmployeeId).collect(toSet());
			Map<Long, String> employeeNameMap = iEmployeeService.getBaseMapper().selectBatchIds(employeeIdSet).stream().collect(Collectors.toMap(WwEmployee::getId, WwEmployee::getName));
			contactEmployeeList.forEach(ce->ce.setEmployeeName(employeeNameMap.get(ce.getEmployeeId())));
			contactVo.setContactEmployeeList(contactEmployeeList);
			//处理归属成员 end

			//处理标签 begin
			Set<Long> contactTagId = iWwContactTagPivotService.lambdaQuery()
				.select(WwContactTagPivot::getTagId)
				.eq(WwContactTagPivot::getContactId, contactVo.getId())
				.list()
				.stream()
				.map(WwContactTagPivot::getTagId)
				.collect(toSet());
			if (!contactTagId.isEmpty()){
				List<WwTag> tags = iTagService.lambdaQuery().in(WwTag::getId, contactTagId).list();
				contactVo.setTags(tags);
			}
		});
		return PageUtils.buildDataInfo(result);
	}
	private LambdaQueryWrapper<WwContact> buildQueryWrapper(WwContactQueryBo bo) {
		Map<String, Object> params = bo.getParams();
		LambdaQueryWrapper<WwContact> lqw = Wrappers.lambdaQuery();
		lqw.like(StringUtil.isNotBlank(bo.getName()), WwContact::getName, bo.getName());
		lqw.like(StringUtil.isNotBlank(bo.getNickName()), WwContact::getNickName, bo.getNickName());
		lqw.eq(bo.getFollowUpStatus() != null, WwContact::getFollowUpStatus, bo.getFollowUpStatus());
		lqw.eq(bo.getType() != null, WwContact::getType, bo.getType());
		lqw.like(StringUtil.isNotBlank(bo.getCorpName()), WwContact::getCorpName, bo.getCorpName());
		lqw.like(StringUtil.isNotBlank(bo.getCorpFullName()), WwContact::getCorpFullName, bo.getCorpFullName());
		lqw.eq(StringUtil.isNotBlank(bo.getExternalProfile()), WwContact::getExternalProfile, bo.getExternalProfile());
		lqw.eq(StringUtil.isNotBlank(bo.getBusinessNo()), WwContact::getBusinessNo, bo.getBusinessNo());
		return lqw;
	}


	/**
	 * @description 同步客户
	 * @author zhaojinjian
	 * @createTime 2020/12/12 11:43
	 */
	@Override
	@Transactional
	public void syncContact(Long corpId) {
		SyncContactSummary summary = new SyncContactSummary();
		summary.setCorpId(corpId);
		log.debug("开始同步 contact....");
		//根据成员Employee.wxUserId获取所有客户
		// map结构{wxUserId,employeeId}
		Map<String, Long> wxUserIdAndEmployeeIdMap = iEmployeeService.lambdaQuery()
			.select(WwEmployee::getWxUserId, WwEmployee::getId)
			.eq(WwEmployee::getCorpId, corpId)
			.list()
			.stream()
			.collect(Collectors.toMap(WwEmployee::getWxUserId, WwEmployee::getId));

		summary.setEmployeeCnt(wxUserIdAndEmployeeIdMap.size());
		log.debug(String.format("本次共需要同步%d个employee的contact信息", wxUserIdAndEmployeeIdMap.size()));

		Map<String, Long> localExternalIdAndContactMap = this.lambdaQuery()
			.select(WwContact::getWxExternalUserid, WwContact::getId)
			.eq(WwContact::getCorpId, corpId)
			.list()
			.stream()
			.collect(Collectors.toMap(c->c.getWxExternalUserid(), c->c.getId()));

		summary.setLocalContactCnt(localExternalIdAndContactMap.size());
		log.debug(String.format("本地共有%d个contact",localExternalIdAndContactMap.size()));


		Set<String> wxUserIdSet = wxUserIdAndEmployeeIdMap.keySet().stream().collect(toSet());
		//根据成员微信id获取成员下客户列表
		Set<String> externalUserIdSet = iExternalContactService.getAllExternalUserId(wxUserIdSet, corpId);
		summary.setRemoteContactCnt(externalUserIdSet.size());
		log.debug(String.format("本次远端共有%d个外部联系人",externalUserIdSet.size()));

		//根据成员微信id数组，获取多个微信客户详细信息
		Set<ExternalContactResp> remoteExternalContactSet = iExternalContactService.getExternalContact(externalUserIdSet, corpId);
		summary.setRemoteContactDetailCnt(remoteExternalContactSet.size());
		log.debug(String.format("本次总共从远端获取到%d个联系人的详细信息",remoteExternalContactSet.size()));
		for (ExternalContactResp resp : remoteExternalContactSet){
			String externalUserid = resp.getContact().getWxExternalUserid();
			Long localContactId = localExternalIdAndContactMap.get(externalUserid);
			if (localContactId == null){
				//insert
				summary.setAddContactCnt(summary.getAddContactCnt()+1);
				this.addContact(corpId,resp,null);
			}else{
				//update
				summary.setUpdateContactCnt(summary.getUpdateContactCnt()+1);
				WwContact contact = this.getById(localContactId);
				this.updateContact(corpId,resp,contact,null);
			}
		}
		log.debug(summary.toString());
	}

	@Override
	public WwContactVo getContactVoByWxUserid(String wxUserId){
		WwContact contact = this.lambdaQuery().eq(WwContact::getWxExternalUserid, wxUserId).one();
		WwContactVo vo = BeanUtil.toBean(contact, WwContactVo.class);
		return vo;
	}
	@Override
	public WwContact getContactByWxUserid(String wxUserId){
		WwContact contact = this.baseMapper.getContactByWxExternalUserid(wxUserId);
		return contact;
	}
	@Override
	public boolean restoreByWxUserid(String wxUserId){
		return this.baseMapper.restoreByWxExternalUserid(wxUserId);
	}
	@Override
	public WwContact addContact(Long corpId, ExternalContactResp resp, String employeeWxUserid){
		WwContact remoteContact = resp.getContact();
		remoteContact.setCorpId(corpId);
		String wxAvatarUrl = remoteContact.getAvatar();
		String avatarPath = FileUtils.getContactAvatarPath(corpId,wxAvatarUrl);
		remoteContact.setAvatar(avatarPath);

		//首次被添加
		WwContactEmployee firstAddEmployee = employeeWxUserid == null ? resp.getFirstAddEmployee() : resp.getContactEmployee(employeeWxUserid);
		remoteContact.setAddTime(firstAddEmployee.getAddTime());
		remoteContact.setAddWay(firstAddEmployee.getAddWay());
		try{
			this.save(remoteContact);
		}catch (DuplicateKeyException e){
			//可能被删除过，从删除状态恢复出来
			this.restoreByWxUserid(remoteContact.getWxExternalUserid());
			WwContact contact = this.getContactByWxUserid(remoteContact.getWxExternalUserid());
			remoteContact.setId(contact.getId());
		}

		//更新头像
		AliyunUpload.uploadStream(wxAvatarUrl,avatarPath);

		resp.getContactEmployeeList().forEach(rCe->{
			WwEmployee employee = iEmployeeService.getByWxUserid(rCe.getEmployeeWxUserid());
			//TODO 如果这个employee不存在，则需要先根据employeeWxUserid同步employee
			this.addContactEmployee(corpId,rCe,remoteContact,employee);
		});
		return remoteContact;
	}
	@Override
	public void updateContact(Long corpId, ExternalContactResp resp, WwContact contact, String employeeWxUserid){
		WwContact remoteContact = resp.getContact();
		String wxAvatarUrl = remoteContact.getAvatar();
		String newAvatarPath = FileUtils.getContactAvatarPath(corpId,wxAvatarUrl);
		boolean isUpdated = this.lambdaUpdate()
			.set(WwContact::getAvatar, newAvatarPath)
			.ne(WwContact::getAvatar, newAvatarPath)
			.eq(WwContact::getId, contact.getId())
			.update();
		if (isUpdated){
			AliyunUpload.uploadStream(wxAvatarUrl,newAvatarPath);
		}
		if (employeeWxUserid == null){
			List<WwContactEmployee> remoteContactEmployeeList = resp.getContactEmployeeList();
			//取出所有
			List<WwContactEmployee> localContactEmployeeList = iContactEmployeeService.lambdaQuery()
				.eq(WwContactEmployee::getCorpId, corpId)
				.eq(WwContactEmployee::getContactId, contact.getId())
				.list();
			Set<String> localEmployeeWxUserIdSet = localContactEmployeeList.stream().map(lce -> lce.getEmployeeWxUserid()).collect(toSet());
			Set<String> remoteEmployeeWxUserIdSet = remoteContactEmployeeList.stream().map(rce -> rce.getEmployeeWxUserid()).collect(toSet());
			//待删除contactEmployeeList
			List<WwContactEmployee> delContactEmployeeList = localContactEmployeeList.stream()
				.filter(lce -> !remoteEmployeeWxUserIdSet.contains(lce.getEmployeeWxUserid()))
				.collect(toList());
			//待新增contactEmployeeList
			List<WwContactEmployee> addContactEmployeeList = remoteContactEmployeeList.stream()
				.filter(rce -> !localEmployeeWxUserIdSet.contains(rce.getEmployeeWxUserid()))
				.collect(toList());
			//待更新contactEmployeeList
			List<WwContactEmployee> updateContactEmployeeList = remoteContactEmployeeList.stream()
				.filter(rce -> localEmployeeWxUserIdSet.contains(rce.getEmployeeWxUserid()))
				.collect(toList());
			//批量更新
			updateContactEmployeeList.forEach(remoteContactEmployee->{
				WwEmployee employee = iEmployeeService.getByWxUserid(remoteContactEmployee.getEmployeeWxUserid());
				updateContactEmployee(corpId, remoteContactEmployee, contact, employee);
			});
			//批量新增
			addContactEmployeeList.forEach(rce->{
				WwEmployee employee = iEmployeeService.getByWxUserid(rce.getEmployeeWxUserid());
				addContactEmployee(corpId,rce,contact,employee);
			});
			//批量删除
			delContactEmployeeList.forEach(lce->{
				WwEmployee employee = iEmployeeService.getByWxUserid(lce.getEmployeeWxUserid());
				//这里假设为员工删客户
				delContactEmployeeByEmployee(corpId,contact,employee);
			});
		}else{

			WwContactEmployee remoteContactEmployee = resp.getContactEmployee(employeeWxUserid);
			WwContactEmployee localContactEmployee = iContactEmployeeService.lambdaQuery()
				.eq(WwContactEmployee::getCorpId, corpId)
				.eq(WwContactEmployee::getContactId, contact.getId())
				.eq(WwContactEmployee::getEmployeeWxUserid, employeeWxUserid)
				.one();
			WwEmployee employee = iEmployeeService.getByWxUserid(employeeWxUserid);
			//新增
			if (localContactEmployee == null){
				addContactEmployee(corpId,remoteContactEmployee,contact,employee);
			}
			//更新
			else{
				updateContactEmployee(corpId, remoteContactEmployee, contact, employee);
			}
		}
	}
	private void addContactEmployee(Long corpId, WwContactEmployee remoteContactEmployee, WwContact contact, WwEmployee employee){
		TrackEventEnum event = TrackEventEnum.CONTACT_ADD;
		String message = generateContactAddMsg(remoteContactEmployee.getAddWay(),remoteContactEmployee.getState(),employee);
		//首次成为好友
		remoteContactEmployee.setCorpId(corpId);
		remoteContactEmployee.setContactId(contact.getId());
		remoteContactEmployee.setEmployeeId(employee.getId());
		remoteContactEmployee.setEmployeeWxUserid(employee.getWxUserId());
		remoteContactEmployee.setEmployeeName(employee.getName());
		try{
			iContactEmployeeService.save(remoteContactEmployee);
		}catch (DuplicateKeyException e){
			//违反唯一索引(contact_id,employee_id,corp_id,del_flag) 说明可能是删除好友后del_flag状态未更新，再次添加就会抛此异常
			iContactEmployeeService.restore(contact.getWxExternalUserid(),employee.getWxUserId());
			event = TrackEventEnum.CONTACT_ADD_REPEAT;
			log.debug(e.getMessage());
		}
		//添加互动轨迹
		iWwContactTrackService.addTrack(corpId, event,contact,employee,message);
		//添加标签
		List<WwContactTagPivot> localTagList = iWwContactTagPivotService.lambdaQuery()
			.eq(WwContactTagPivot::getCorpId, corpId)
			.eq(WwContactTagPivot::getContactId, contact.getId())
			.eq(WwContactTagPivot::getEmployeeId, employee.getId())
			.list();
		List<WwContactTagPivot> remoteTagList = remoteContactEmployee.getTagPivotList();
		//添加标签
		addTag(corpId,contact,employee,remoteTagList,localTagList);
	}
	@Override
	public void delContactEmployeeByEmployee(Long corpId,WwContact contact,WwEmployee employee){
		//添加互动轨迹
		String message = String.format("%s删除了联系人", employee.getName());
		iWwContactTrackService.addTrack(corpId, TrackEventEnum.CONTACT_DEL_BY_EMPLOYEE,contact,employee,message);
		delContactEmployee(corpId,contact,employee);
	}
	@Override
	public void delContactEmployeeByContact(Long corpId,WwContact contact,WwEmployee employee){
		//添加互动轨迹
		String message = String.format("%s被联系人删除", employee.getName());
		iWwContactTrackService.addTrack(corpId, TrackEventEnum.CONTACT_DEL_BY_CONTACT,contact,employee,message);
		delContactEmployee(corpId,contact,employee);
	}
	private void delContactEmployee(Long corpId,WwContact contact,WwEmployee employee){
		iContactEmployeeService.lambdaUpdate()
			.eq(WwContactEmployee::getCorpId,corpId)
			.eq(WwContactEmployee::getContactId,contact.getId())
			.eq(WwContactEmployee::getEmployeeWxUserid,employee.getWxUserId())
			.remove();
		int employeeCnt = iContactEmployeeService.count(new LambdaQueryWrapper<WwContactEmployee>().eq(WwContactEmployee::getContactId, contact.getId()));
		//已删除所有员工，记录下来
		if (employeeCnt == 0){
			//逻辑删除
			this.removeById(contact.getId());
			String message = TrackEventEnum.CONTACT_DEL_All.getLabel();//与所有成员都不是好友关系
			iWwContactTrackService.addTrack(corpId, TrackEventEnum.CONTACT_DEL_BY_CONTACT,contact,employee,message);
		}
		//TODO 删除标签,已被删除好友关系，标签可暂时可以不处理
	}

	private void updateContactEmployee(Long corpId, WwContactEmployee remoteContactEmployee, WwContact contact, WwEmployee employee) {
		WwContactEmployee lCe = iContactEmployeeService.lambdaQuery()
			.eq(WwContactEmployee::getCorpId, corpId)
			.eq(WwContactEmployee::getContactId, contact.getId())
			.eq(WwContactEmployee::getEmployeeId, employee.getId())
			.one();

		boolean isChangeRemark = !WxStringUtils.equals(remoteContactEmployee.getRemark(), lCe.getRemark());
		boolean isChangeDescription = !WxStringUtils.equals(remoteContactEmployee.getDescription(), lCe.getDescription());
		boolean isChangeMobile = !WxStringUtils.equals(remoteContactEmployee.getRemarkMobiles(), lCe.getRemarkMobiles());
		boolean isChangeCorpName = !WxStringUtils.equals(remoteContactEmployee.getRemarkCorpName(), lCe.getRemarkCorpName());

		iContactEmployeeService.lambdaUpdate()
			.set(isChangeRemark, WwContactEmployee::getRemark, remoteContactEmployee.getRemark())
			.set(isChangeDescription, WwContactEmployee::getDescription, remoteContactEmployee.getDescription())
			.set(isChangeMobile, WwContactEmployee::getRemarkMobiles, remoteContactEmployee.getRemarkMobiles())
			.set(isChangeCorpName, WwContactEmployee::getRemarkCorpName, remoteContactEmployee.getRemarkCorpName())
			.set(WwContactEmployee::getUpdateTime, new Date())
			.eq(WwContactEmployee::getId, lCe.getId())
			.update();
		//更新标签
		updateTag(corpId, remoteContactEmployee, contact, employee);
		if (isChangeRemark || isChangeDescription || isChangeMobile || isChangeCorpName){
			//添加互动轨迹
			String message = "";
			message = isChangeRemark ? message+ String.format("备注改为:%s,修改前:%s\n", remoteContactEmployee.getRemark(),lCe.getRemark()) : message;
			message = isChangeDescription ? message+ String.format("描述改为:%s,修改前:%s\n", remoteContactEmployee.getDescription(),lCe.getDescription()) : message;
			message = isChangeMobile ? message+ String.format("手机改为:%s,修改前:%s\n", remoteContactEmployee.getRemarkMobiles(),lCe.getRemarkMobiles()) : message;
			message = isChangeCorpName ? message+ String.format("公司名称改为:%s,修改前:%s\n", remoteContactEmployee.getRemarkCorpName(),lCe.getRemarkCorpName()) : message;
			iWwContactTrackService.addTrack(corpId, TrackEventEnum.CONTACT_EDIT,contact,employee,message);
		}
	}

	private void updateTag(Long corpId, WwContactEmployee remoteContactEmployee, WwContact contact, WwEmployee employee) {
		//处理标签变更
		List<WwContactTagPivot> remoteTagList = remoteContactEmployee.getTagPivotList();
		List<WwContactTagPivot> localTagList = iWwContactTagPivotService.lambdaQuery()
			.eq(WwContactTagPivot::getCorpId, corpId)
			.eq(WwContactTagPivot::getContactId, contact.getId())
			.eq(WwContactTagPivot::getEmployeeId, employee.getId())
			.list();
		delTag(corpId, contact, employee, remoteTagList, localTagList);
		addTag(corpId, contact, employee, remoteTagList, localTagList);
	}

	private void addTag(Long corpId, WwContact contact, WwEmployee employee, List<WwContactTagPivot> remoteTagList, List<WwContactTagPivot> localTagList) {
		List<WwTag> tagList = iTagService.lambdaQuery()
			.eq(WwTag::getCorpId, corpId)
			.list();
		Map<String, Long> tagMap = tagList.stream().collect(Collectors.toMap(t -> t.getWxTagId(), t -> t.getId()));
		//新增tag
		List<WwContactTagPivot> newTagPivotList = remoteTagList.stream()
			.filter(rTag -> !containTag(localTagList,rTag))
			.collect(toList());
		newTagPivotList.forEach(tp->{
			tp.setCorpId(corpId);
			tp.setContactId(contact.getId());
			tp.setEmployeeId(employee.getId());
			Long tagId = tagMap.get(tp.getWxTagId());
			tp.setTagId(tagId);
		});
		if (newTagPivotList.isEmpty()){
			return;
		}
		iWwContactTagPivotService.saveBatch(newTagPivotList);

		// 互动轨迹
		String message = "添加了标签:";
		String tagNames = newTagPivotList.stream().map(t->t.getTagName()).reduce((tags,item)->tags += item+",").orElse("");;
		message += tagNames;
		iWwContactTrackService.addTrack(corpId, TrackEventEnum.CONTACT_DEL_TAG,contact,employee,message);
	}
	private void delTag(Long corpId,WwContact contact,WwEmployee employee,List<WwContactTagPivot> remoteTagList, List<WwContactTagPivot> localTagList) {
		//删除tag
		List<WwContactTagPivot> delTagPivotList = localTagList.stream()
			.filter(lTag->!containTag(remoteTagList,lTag))
			.collect(toList());
		Set<Long> delTagIdSet = delTagPivotList.stream().map(t -> t.getId()).collect(toSet());
		if (delTagIdSet.isEmpty()){
			return;
		}
		List<WwContactTagPivot> delTagList = iWwContactTagPivotService.listByIds(delTagIdSet);
		iWwContactTagPivotService.removeByIds(delTagIdSet);
		// 互动轨迹
		String message = "删除了标签:";
		String tagNames = delTagList.stream().map(t->t.getTagName()).reduce((tags,item)->tags += item+",").orElse("");
		message += tagNames;
		iWwContactTrackService.addTrack(corpId, TrackEventEnum.CONTACT_DEL_TAG,contact,employee,message);
	}

	/**
	 * 判断是否包含相同标签
	 * @param tagList
	 * @param tag
	 * @return
	 */
	private boolean containTag(List<WwContactTagPivot> tagList,WwContactTagPivot tag){
		for (WwContactTagPivot tagPivot:tagList){
			if (tagPivot.getId() == tag.getId() && tag.getId() != null){
				return true;
			}else if(tagPivot.getTagId() == tag.getTagId() && tag.getTagId() != null ){
				return true;
			}
			//wxTagId不为空，且值相同
			else if(StringUtils.isNotBlank(tagPivot.getWxTagId())
				&& StringUtils.equals(tagPivot.getWxTagId(),tag.getWxTagId())){
				return true;
			}
			//标签类型相同(都为企业标签或都为个人标签)，且wxTagId都为空，那么根据标签名称判断，标签名称相同
			else if (tagPivot.getType() == tag.getType()
				&& StringUtils.isBlank(tagPivot.getWxTagId())
				&& StringUtils.isBlank(tag.getWxTagId())
				&& StringUtils.equals(tagPivot.getTagName(),tag.getTagName())){
				return true;
			}
		}
		return false;
	}

	/**
	 * 生成添加客户时的互动轨迹消息track message
	 * @param addWay
	 * @param state
	 * @param employee
	 * @return
	 */
	private String generateContactAddMsg(Integer addWay,String state,WwEmployee employee){
		String addWayText = "未知来源";
		if (addWay != null){
			addWayText = iSysDictDataService.selectDictLabel("contact_wx_addway",String.valueOf(addWay));
		}

		ContactAddwayState addState = null;
		String message = "";

		if (StringUtils.isNotBlank(state)){
			try{
				addState = JSONObject.parseObject(state,ContactAddwayState.class);
			}catch (Exception e){
				log.debug("error state:"+state);
			}
		}
		if (addState != null && addState.getType() == ContactAddwayStateEnum.YiKeYiMa){
			//一客一码的联系人
			WwContactEmployee yikeyimaContact = iContactEmployeeService.getById(addState.getId());
			WwContact invitor = this.getById(yikeyimaContact.getContactId());
			//与%s成为好友,渠道:一客一码(李四)来源:扫描二维码
			message = String.format("与 %s 成为好友,渠道: %s(%s),来源: %s",
				employee.getName(),
				ContactAddwayStateEnum.YiKeYiMa.getLabel(),
				invitor.getName(),
				addWayText);
		}else{
			//与%s成为好友，来源:%s
			message = String.format("与 %s 成为好友,来源: %s", employee.getName(),addWayText);
		}
		return message;
	}
}
